//
//  ViewControllerExtension.swift
//  MT
//
//  Created by zhang qiang on 2018/12/2.
//  Copyright © 2019年 张强. All rights reserved.
//

import Foundation
import SnapKit
import UIKit

/// 加载数据失败原因
///
/// - network: 无网络
/// - server: 服务器失败
public enum LoadDataFailedReason{
    case network
    case server
}

fileprivate struct AssociatedKeys{
    static var SocketLoadingView: UInt8 = 0
    static var ServerCrashView: UInt8 = 0
    static var NoNetworkView: UInt8 = 0
    static var HudLoadingView: UInt8 = 0
    static var ToastView: UInt8 = 0
}


/// 刷新视图协议
public protocol  RefreshView {
    func refreshView()
}


// MARK: - 数据加载动画扩展
public extension UIViewController {
    
    internal var socketLoadingView: MTLoadingView? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.SocketLoadingView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTLoadingView? = objc_getAssociatedObject(self, &AssociatedKeys.SocketLoadingView) as? MTLoadingView
            return obj
        }
    }
    
    internal var serverCrashView: MTServerCrachView? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.ServerCrashView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTServerCrachView? = objc_getAssociatedObject(self, &AssociatedKeys.ServerCrashView) as? MTServerCrachView
            return obj
        }
    }
    
    internal var noNetworkView: MTNoNetworkView? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.NoNetworkView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTNoNetworkView? = objc_getAssociatedObject(self, &AssociatedKeys.NoNetworkView) as? MTNoNetworkView
            return obj
        }
    }
    
//    public func startLoading() -> Void{
//        if let view = circleLoadingView{
//            view.removeFromSuperview()
//        }else{
//            circleLoadingView = MTHudLoadingView()
//            self.view.addSubview(circleLoadingView!)
//            circleLoadingView!.snp.makeConstraints({ (make) in
//                make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
//            })
//        }
//    }
    
    func startLoading() -> Void{

        if let view = circleLoadingView{
            self.view.bringSubviewToFront(view)
        }else{
            circleLoadingView = MTHudLoadingView()
            self.view.addSubview(circleLoadingView!)

            circleLoadingView!.snp.makeConstraints({ (make) in
                make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
            })
        }
    }
    
    func loadDataSuccess() -> Void{
        /// 加载完成后 不会再需要相关view 全部删除
        if let view = socketLoadingView{
            view.removeFromSuperview()
            socketLoadingView = nil
        }

        if let view = serverCrashView{
            view.removeFromSuperview()
            serverCrashView = nil
        }

        if let view = noNetworkView{
            view.removeFromSuperview()
            noNetworkView = nil
        }
        if let view = circleLoadingView{
            view.removeFromSuperview()
        }
        
    }
    
    func loadDataFailed(reason : LoadDataFailedReason){
        switch reason {
        case .network:
            if let view = noNetworkView{
                self.view.bringSubviewToFront(view)
            }else{
                noNetworkView = MTNoNetworkView()
                noNetworkView?.refreshClosure = {
                    if let vc = self as? RefreshView{
                        /// 如果实现了RefreshView协议
                        vc.refreshView()
                    }
                }
                self.view.addSubview(noNetworkView!)
                noNetworkView!.snp.makeConstraints({ (make) in
                    make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
                })
            }
            
        case .server:
            if let view = serverCrashView{
                self.view.bringSubviewToFront(view)
            }else{
                serverCrashView = MTServerCrachView()
                serverCrashView?.refreshClosure = {
                    
                    /// 如果实现了RefreshView协议
                    if let vc = self as? RefreshView{
                        vc.refreshView()
                    }
                }
                self.view.addSubview(serverCrashView!)
                serverCrashView!.snp.makeConstraints({ (make) in
                    make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
                })
            }
        }
    }
    
}

public extension UIViewController{
    internal var circleLoadingView: MTHudLoadingView? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.HudLoadingView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTHudLoadingView? = objc_getAssociatedObject(self, &AssociatedKeys.HudLoadingView) as? MTHudLoadingView
            return obj
        }
    }
    
    internal var toastView: MTTostaView? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.ToastView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTTostaView? = objc_getAssociatedObject(self, &AssociatedKeys.ToastView) as? MTTostaView
            return obj
        }
    }
    
    func showHudLoadingView() -> Void{
        if let view = circleLoadingView{
            view.removeFromSuperview()
            circleLoadingView = MTHudLoadingView()
            self.view.addSubview(circleLoadingView!)
            circleLoadingView!.snp.makeConstraints({ (make) in
                make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
            })
        }else{
            circleLoadingView = MTHudLoadingView()
            self.view.addSubview(circleLoadingView!)
            circleLoadingView!.snp.makeConstraints({ (make) in
                make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
            })
        }
    }
    
    func hideHudLoadingView() -> Void{
        if let view = circleLoadingView{
            view.removeFromSuperview()
        }
    }
    
    func showToast(image: ToastIcon, text: String, duration: TimeInterval = 3) -> Void {
        toastView = MTTostaView(image: image, text: text, width: 120)
        self.view.addSubview(toastView!)
        toastView!.snp.makeConstraints({ (make) in
            make.edges.equalTo(self.view).inset(UIEdgeInsets.zero)
        })
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
            self.hideToast()
        }
    }
    
    func hideToast() -> Void {
        if let view = toastView {
            view.removeFromSuperview()
        }
    }
    
    @objc func backButton() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .done, target: self, action: #selector(pop))
    }
    
    @objc func pop() {
        if self.navigationController != nil &&
            self.navigationController!.viewControllers.count > 1 {
            self.navigationController?.popViewController(animated: true)
        }
    }
}
